package com.lu.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.common.constants.ApUserExamineContants;
import com.lu.common.constants.WmNewConstants;
import com.lu.common.constants.WmNewsShelfConstants;
import com.lu.common.exception.CustomException;
import com.lu.model.admin.dto.ArticleExamineDto;
import com.lu.model.admin.dto.NewsAuthDto;
import com.lu.model.article.dto.ArticleDto;
import com.lu.model.common.dtos.PageResponseResult;
import com.lu.model.common.dtos.ResponseResult;
import com.lu.model.common.enums.AppHttpCodeEnum;
import com.lu.model.wemedia.dto.WmArticleDto;
import com.lu.model.wemedia.dto.WmNewsDto;
import com.lu.model.wemedia.pojo.*;
import com.lu.utils.thread.WmThreadLocalUtil;
import com.lu.wemedia.mapper.WmNewsMapper;
import com.lu.wemedia.mapper.WmFileMapper;
import com.lu.wemedia.mapper.WmNewsMaterialMapper;
import com.lu.wemedia.service.IWmNewsAutoExamineService;
import com.lu.wemedia.service.WmNewsService;
import com.lu.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmFileMapper wmFileMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private IWmNewsAutoExamineService wmNewsAutoExamineService;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmNewsAutoTaskServiceImpl wmNewsAutoTaskService;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private WmUserService wmUserService;


    /**
     * 查询文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listArticle(WmArticleDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //获取用户
        WmUser user = WmThreadLocalUtil.getWmUser();
        //分页
        Page<WmNews> newsPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper();
        //状态，草稿，是否审核通过
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //频道
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //发布时间
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //只查询当前用户的文章
        wrapper.eq(WmNews::getUserId, user.getId());
        //时间倒叙排列
        wrapper.orderByDesc(WmNews::getCreatedTime);

        //构造分页
        Page<WmNews> page = this.page(newsPage, wrapper);

        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 发布文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //校验参数
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存，修改
        WmNews wmNews = new WmNews();
        //保存
        BeanUtils.copyProperties(dto, wmNews);
        //图片传进来的是集合，需要转为字符串
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }
        //如果自动设置封面，前端传入-1，设置为null
        if (dto.getType().equals(WmNewConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }

        saveOrUpdateWmNews(wmNews);

        //草稿就结束
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //不是就保存，同时保存文章里的图片和素材的对应关系,同时如果布局是自动，需要自动匹配封面图片
        //获取文章的所有图片，这里面保存的是图片的地址，文章内容，type
        List<String> materials = getImagesFromWm(dto.getContent());
        //保存文章内容图片和素材的关系
        saveRelationWmNews(materials, wmNews.getId());
        //保存文章封面图片和素材的关系,同时根据自动布局，匹配图片
        saveRelationCover(dto, wmNews, materials);

        //审核文章
        //wmNewsAutoExamineService.autoExamine(wmNews.getId());
        //现在使用延时任务
        wmNewsAutoTaskService.addNewsToTsk(wmNews.getId(), wmNews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 保存文章内容图片和素材的关系
     * @param materials
     * @param newsId
     */
    public void saveRelationWmNews(List<String> materials, Integer newsId) {
        saveRelationInfo(materials, newsId, WmNewConstants.WM_CONTENT_REFERENCE);
    }


    /**
     * 保存关系
     * @param materials
     * @param newsId
     * @param type
     */
    public void saveRelationInfo(List<String> materials, Integer newsId, Short type) {
        //图片不能为空
        if (materials != null && !materials.isEmpty()) {
            //根据图片地址获取图片
            List<WmMaterial> wmMaterials = wmFileMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
            //校验
            if (wmMaterials == null || wmMaterials.size() == 0) {
               //必须手动抛出异常,进行数据回滚
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            if (materials.size() != wmMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }
            //获取图片id
            List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            //批量保存
            wmNewsMaterialMapper.saveRelations(ids, newsId, type);

        }
    }


    /**
     * 自动设置封面图片
     * 1-3（单图，type=1）
     * >=3(多图，type=3)
     * 0(无图，type=0)
     * 同时保存封面图片和素材的关系
     * @param dto
     * @param wmNews
     * @param materials
     */
    public void saveRelationCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        //图片
        List<String> images = dto.getImages();
        //自动设置封面
        if (dto.getType().equals(WmNewConstants.WM_NEWS_TYPE_AUTO)) {
            //多图
            if (images.size() >= 3) {
                wmNews.setType(WmNewConstants.WM_NEWS_MANY_IMAGE);
                images = images.stream().limit(3).collect(Collectors.toList());
            } else if (images.size() >= 1 && images.size() < 3) {
                //单图
                images = images.stream().limit(1).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType(WmNewConstants.WM_NEWS_NONE_IMAGE);
            }
        }
        //修改文章
        if(images != null && images.size() > 0){
            wmNews.setImages(StringUtils.join(images,","));
        }
        this.updateById(wmNews);
        if(images != null && images.size() > 0){
            saveRelationInfo(images,wmNews.getId(),WmNewConstants.WM_COVER_REFERENCE);
        }
    }




    /**
     * 提取文章内容中的图片信息
     * @param content
     * @return
     */
    public List<String> getImagesFromWm(String content) {
        List<String> imagesUrls = new ArrayList<>();

        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                String imaUrl = (String) map.get("value");
                imagesUrls.add(imaUrl);
            }
        }
        return imagesUrls;
    }


    /**
     * 保存，修改文章
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getWmUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short)1);//默认上架

        if(wmNews.getId() == null){
            //保存
            this.save(wmNews);
        }else {
            //修改
            //删除文章图片与素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            this.updateById(wmNews);
        }

    }





    /**
     * 文章详细信息
     * @param id
     * @return
     */
    @Override
    public ResponseResult message(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = wmNewsMapper.selectOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id));
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(wmNews);
    }


    /**
     * 删除文章
     * @param id
     * @return
     */
    @Override
    public int deleteById(Integer id) {
        if (id == null) {
            return WmNewConstants.FAIL_RESULT_CODE;
        }
        return wmNewsMapper.deleteById(id);
    }




    /**
     * 文章上下架
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章ID不可缺少");
        }
        WmNews wmNews = wmNewsMapper.selectOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId()));
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FAIL, "当前文章未发布,不能上架!");
        }
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
            this.update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, dto.getEnable()).eq(WmNews::getId, wmNews.getId()));
            //通知app端上下架文章
            if (wmNews.getArticleId() != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("articleId", wmNews.getArticleId());
                map.put("enable", wmNews.getEnable());
                kafkaTemplate.send(WmNewsShelfConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 文章人工审核列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult artificialExamine(NewsAuthDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(WmNews::getStatus, dto.getStatus());
        queryWrapper.like(WmNews::getTitle, dto.getTitle());
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        Page<WmNews> data = this.page(page, queryWrapper);

        List<WmNews> records = data.getRecords();
        List<Serializable> collect = records.stream().map((item) -> {
            ArticleExamineDto examineDto = new ArticleExamineDto();
            BeanUtils.copyProperties(item, examineDto);
            //设置作者姓名
            Integer userId = item.getUserId();
            WmUser wmUser = wmUserService.getById(userId);
            if (wmUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            examineDto.setAuthorName(wmUser.getName());
            return examineDto;
        }).collect(Collectors.toList());

        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) data.getTotal());

        result.setData(collect);

        return result;
    }


    /**
     * 查询人工审核的文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findArticle(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ArticleExamineDto dto = new ArticleExamineDto();
        BeanUtils.copyProperties(wmNews, dto);
        dto.setAuthorName(wmUserService.getById(wmNews.getUserId()).getName());

        return ResponseResult.okResult(dto);
    }


    /**
     * 人工审核失败
     * @param dto
     * @return
     */
    @Override
    public ResponseResult examineFail(NewsAuthDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer id = dto.getId();
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wmNews.setStatus(ApUserExamineContants.EXAMINE_FAIL);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 人工审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult examineSuccess(NewsAuthDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer id = dto.getId();
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wmNews.setStatus(ApUserExamineContants.EXAMINE_PERSON_PASS);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
